package com.xianniu.ltc.service.impl;

import cn.devezhao.persist4j.Entity;
import cn.devezhao.persist4j.Record;
import cn.devezhao.persist4j.engine.ID;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rebuild.core.Application;
import com.rebuild.core.UserContextHolder;
import com.rebuild.core.metadata.EntityHelper;
import com.rebuild.core.metadata.MetadataHelper;
import com.rebuild.core.metadata.easymeta.EasyMetaFactory;
import com.rebuild.core.privileges.UserHelper;
import com.rebuild.core.privileges.UserService;
import com.rebuild.core.privileges.bizz.User;
import com.rebuild.core.service.NoRecordFoundException;
import com.rebuild.core.service.approval.ApprovalHelper;
import com.rebuild.core.service.approval.ApprovalState;
import com.rebuild.core.support.ConfigurationItem;
import com.rebuild.core.support.RebuildConfiguration;
import com.rebuild.core.support.general.FieldValueHelper;
import com.xianniu.ltc.common.Constant;
import com.xianniu.ltc.enums.*;
import com.xianniu.ltc.mapper.*;
import com.xianniu.ltc.model.entity.*;
import com.xianniu.ltc.model.po.*;
import com.xianniu.ltc.model.vo.*;
import com.xianniu.ltc.service.ExternalService;
import com.xianniu.ltc.util.NameUtil;
import com.xxl.sso.core.entity.ReturnT;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author WangRuiJie
 * @Title: ExternalServiceImpl
 * @Package com.xianniu.ltc.service.impl
 * @Description: 外部接口实现类
 * @date 2021/5/314:59 下午
 */
@Slf4j
@Service
public class ExternalServiceImpl implements ExternalService {

    // 默认密码123456加密
    private final String DEFAULT_PWD = "a03a2ca0a5319a316a7233ce90f4e6f9fe70e8d5579f0abbe59a0e0300bd2404";
    private final String USER_ID = "001-0000000000000001";
    // 系统用户
    public final String SYSTEM_USER = "001-0000000000000000";
    private final String DEPT_ID = "002-0000000000000001";
    private final String ROLE_ID= "003-0000000000000001";

    private final String ACCOUNT_ID_1= "061-0000000000000001";
    private final String ACCOUNT_ID_2= "061-0000000000000002";

    private final String LEAD_ID_1= "059-0000000000000001";
    private final String LEAD_ID_2= "059-0000000000000002";


    @Resource
    private ClassificationDataMapper classificationDataMapper;
    @Resource
    private TYingjicaigoudingdanMapper yingjicaigoudingdanMapper;

    @Resource
    private TJihuacaigoudingdanshangpinMapper jihuacaigoudingdanshangpinMapper;

    @Resource
    private TJihuacaigouxiangmuMapper jihuacaigouxiangmuMapper;

    @Resource
    private TCaigoushouhoudingdanshangpinMapper caigoushouhoudingdanshangpinMapper;

    @Resource
    private TXiangmuleifukuanMapper xiangmuleifukuanMapper;

    @Resource
    private TJiaofushijianguanliMapper jiaofuMapper;

    @Resource
    private TShoujianfuwuqingqiuMapper shoujianfuwuqingqiuMapper;

    @Resource
    private TCaigoushijianguanliMapper caigouMapper;
    @Resource
    private TUserMapper tUserMapper;
    @Resource
    private  TDepartmentMapper tDepartmentMapper;
    @Resource
    private TRoleMapper tRoleMapper;

    @Resource
    private THetongxiangqingMapper hetongxiangqingMapper;

    @Resource
    private TShebeimingxibuxiaoMapper shebeimingxibuxiaoMapper;

    @Resource
    private TRbhetong0Mapper rbhetong0Mapper;

    @Resource
    private TBaojiaxietongMapper baojiaxietongMapper;

    @Resource
    private TQuotationMapper quotationMapper;

    @Resource
    private  TProjectReportMapper tProjectReportMapper;

    @Resource
    private TXnAccountTeamMapper accountTeamMapper;

    @Resource
    private TXnLeadTeamMapper leadTeamMapper;

    @Resource
    private TGongyingshangguanliMapper gongyingshangguanliMapper;

    @Resource
    private TShebeimingxichaonengbaoMapper shebeimingxichaonengbaoMapper;

    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Resource
    private RobotApprovalStepMapper robotApprovalStepMapper;

    @Resource
    private TCaiGouDingDanGuiJiMapper caiGouDingDanGuiJiMapper;

    @Resource
    private TCaiGouDingDanMingXiGuiJiMapper caiGouDingDanMingXiGuiJiMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
    public ReturnT initUser(String loginName, String tenantCode) {
        int result = 0;
        UserContextHolder.setTenant(tenantCode);
        // 校验是否已初始化过销售云
        QueryWrapper<TUserDTO> wrapper = new QueryWrapper<>();
        wrapper.eq("USER_ID", USER_ID);
        wrapper.eq("TENANT_CODE", tenantCode);
        List<TUserDTO> dtos = tUserMapper.selectList(wrapper);
        if (CollectionUtils.isNotEmpty(dtos)){
            log.info("解决企业初始化同步销售成功，但是同步人力云报错导致数据不一致，再次初始化时执行修改逻辑以企业操作台传输参数为准：{}:{}",loginName, tenantCode);
            result = initUpdateUserDto(loginName, tenantCode);
            if (result != 1){
                return ReturnT.FAIL;
            }
        }else {
            // 初始化客户组
            initAccountTeam(tenantCode);
            // 初始化线索组
            initLeadTeam(tenantCode);
            // 初始化部门
            initDept(tenantCode);
            // 初始化角色
            initRole(tenantCode);
            // 初始化用户
            result = initUserDto(loginName, tenantCode);
            if (result != 1){
                return ReturnT.FAIL;
            }
        }
        return ReturnT.SUCCESS;
    }

    /**
     * 客户组初始化全公司，无归属
     * @param tenantCode
     * @return
     */
   private int initAccountTeam(String tenantCode){
       // 新增公私海客户，线索组
       TXnAccountTeamDTO accountTeamDTO1 = new TXnAccountTeamDTO();
       accountTeamDTO1.setTeamId(ACCOUNT_ID_1);
       accountTeamDTO1.setTeamName("全公司");
       accountTeamDTO1.setHeadBy(USER_ID);
       accountTeamDTO1.setRbmiaoshu("系统默认分组，不可编辑和删除，展示数据范围权限范围内所有公海客户（所有成员均可见的公海客户池)");
       accountTeamDTO1.setUseDept(DEPT_ID);
       accountTeamDTO1.setTenantCode(tenantCode);
       accountTeamDTO1.setCreatedBy(String.valueOf(UserService.ADMIN_USER));
       accountTeamDTO1.setCreatedOn(new Date());
       accountTeamDTO1.setModifiedBy(String.valueOf(UserService.ADMIN_USER));
       accountTeamDTO1.setModifiedOn(new Date());
       accountTeamDTO1.setOwningUser(USER_ID);
       accountTeamDTO1.setOwningDept(DEPT_ID);
       accountTeamMapper.insert(accountTeamDTO1);
       TXnAccountTeamDTO accountTeamDTO2 = new TXnAccountTeamDTO();
       accountTeamDTO2.setTeamId(ACCOUNT_ID_2);
       accountTeamDTO2.setTeamName("无归属");
       accountTeamDTO2.setHeadBy(USER_ID);
       accountTeamDTO2.setRbmiaoshu("系统默认无所属（组）的客户池数据分组，不可编辑和删除，仅超级管理员可以查看，管理员可以将客户转移至其他客户池。");
       accountTeamDTO2.setUseDept(DEPT_ID);
       accountTeamDTO2.setTenantCode(tenantCode);
       accountTeamDTO2.setCreatedBy(String.valueOf(UserService.ADMIN_USER));
       accountTeamDTO2.setCreatedOn(new Date());
       accountTeamDTO2.setModifiedBy(String.valueOf(UserService.ADMIN_USER));
       accountTeamDTO2.setModifiedOn(new Date());
       accountTeamDTO2.setOwningUser(USER_ID);
       accountTeamDTO2.setOwningDept(DEPT_ID);
       return accountTeamMapper.insert(accountTeamDTO2);
   }

    /**
     * 线索组初始化全公司，无归属
     * @param tenantCode
     * @return
     */
    private int initLeadTeam(String tenantCode){
        TXnLeadTeamDTO leadTeamDTO1 = new TXnLeadTeamDTO();
        leadTeamDTO1.setTeamId(LEAD_ID_1);
        leadTeamDTO1.setTeamName("全公司");
        leadTeamDTO1.setHeadBy(USER_ID);
        leadTeamDTO1.setRbmiaoshu("系统默认分组，不可编辑和删除，展示数据范围权限范围内所有公海线索（所有成员均可见的公海线索池)");
        leadTeamDTO1.setUseDept(DEPT_ID);
        leadTeamDTO1.setTenantCode(tenantCode);
        leadTeamDTO1.setCreatedBy(String.valueOf(UserService.ADMIN_USER));
        leadTeamDTO1.setCreatedOn(new Date());
        leadTeamDTO1.setModifiedBy(String.valueOf(UserService.ADMIN_USER));
        leadTeamDTO1.setModifiedOn(new Date());
        leadTeamDTO1.setOwningUser(USER_ID);
        leadTeamDTO1.setOwningDept(DEPT_ID);
        leadTeamMapper.insert(leadTeamDTO1);
        TXnLeadTeamDTO leadTeamDTO2 = new TXnLeadTeamDTO();
        leadTeamDTO2.setTeamId(LEAD_ID_2);
        leadTeamDTO2.setTeamName("无归属");
        leadTeamDTO2.setHeadBy(USER_ID);
        leadTeamDTO2.setRbmiaoshu("系统默认无所属（组）的线索池数据分组，不可编辑和删除，仅超级管理员可以查看，管理员可以将线索转移至其他线索池。");
        leadTeamDTO2.setUseDept(DEPT_ID);
        leadTeamDTO2.setTenantCode(tenantCode);
        leadTeamDTO2.setCreatedBy(String.valueOf(UserService.ADMIN_USER));
        leadTeamDTO2.setCreatedOn(new Date());
        leadTeamDTO2.setModifiedBy(String.valueOf(UserService.ADMIN_USER));
        leadTeamDTO2.setModifiedOn(new Date());
        leadTeamDTO2.setOwningUser(USER_ID);
        leadTeamDTO2.setOwningDept(DEPT_ID);
        return leadTeamMapper.insert(leadTeamDTO2);
    }

    /**
     * 部门初始化：总经办
     * @param tenantCode
     * @return
     */
    private int initDept(String tenantCode){
        // 新建部门
        TDepartmentDTO departmentDTO = new TDepartmentDTO();
        departmentDTO.setDeptId(DEPT_ID);
        departmentDTO.setName("总经办");
        departmentDTO.setPrincipalId(USER_ID);
        departmentDTO.setTenantCode(tenantCode);
        departmentDTO.setCreatedBy(String.valueOf(UserService.ADMIN_USER));
        departmentDTO.setCreatedOn(new Date());
        departmentDTO.setModifiedBy(String.valueOf(UserService.ADMIN_USER));
        departmentDTO.setModifiedOn(new Date());
        return tDepartmentMapper.insert(departmentDTO);
    }

    /**
     * 角色初始化：管理员
     * @param tenantCode
     * @return
     */
    private int initRole(String tenantCode){
        //新建角色
        TRoleDTO roleDTO = new TRoleDTO();
        roleDTO.setRoleId(ROLE_ID);
        roleDTO.setName("管理员");
        roleDTO.setTenantCode(tenantCode);
        roleDTO.setCreatedBy(String.valueOf(UserService.ADMIN_USER));
        roleDTO.setCreatedOn(new Date());
        roleDTO.setModifiedBy(String.valueOf(UserService.ADMIN_USER));
        roleDTO.setModifiedOn(new Date());
        return tRoleMapper.insert(roleDTO);
    }

    /**
     * 用户初始化：系统用户，管理员
     * @param tenantCode
     * @return
     */
    private int initUserDto(String loginName,String tenantCode){
        // 新增用户
        TUserDTO dto = new TUserDTO();
        dto.setUserId(USER_ID);
        dto.setLoginName(loginName);
        dto.setPassword(DEFAULT_PWD);
        dto.setFullName(loginName);
        dto.setWorkphone(loginName);
        dto.setDeptId(DEPT_ID);
        dto.setRoleId(ROLE_ID);
        dto.setIsDisabled("F");
        dto.setTenantCode(tenantCode);
        dto.setCreatedBy(String.valueOf(UserService.ADMIN_USER));
        dto.setCreatedOn(new Date());
        dto.setModifiedBy(String.valueOf(UserService.ADMIN_USER));
        dto.setModifiedOn(new Date());
        tUserMapper.insert(dto);
        TUserDTO dto1 = new TUserDTO();
        dto1.setUserId(SYSTEM_USER);
        dto1.setLoginName("system");
        dto1.setPassword(DEFAULT_PWD);
        dto1.setFullName("系统用户");
        dto1.setDeptId(DEPT_ID);
        dto1.setRoleId(ROLE_ID);
        dto1.setIsDisabled("T");
        dto1.setTenantCode(tenantCode);
        dto1.setCreatedBy(String.valueOf(UserService.ADMIN_USER));
        dto1.setCreatedOn(new Date());
        dto1.setModifiedBy(String.valueOf(UserService.ADMIN_USER));
        dto1.setModifiedOn(new Date());
        return tUserMapper.insert(dto1);
    }

    /**
     * 如果租户编码已存在，修改用户初始化：系统用户，管理员
     * @param tenantCode
     * @return
     */
    private int initUpdateUserDto(String loginName,String tenantCode){
        // 新增用户
        TUserDTO dto = new TUserDTO();
        dto.setUserId(USER_ID);
        dto.setLoginName(loginName);
        dto.setPassword(DEFAULT_PWD);
        dto.setFullName(loginName);
        dto.setWorkphone(loginName);
        dto.setDeptId(DEPT_ID);
        dto.setRoleId(ROLE_ID);
        dto.setIsDisabled("F");
        dto.setTenantCode(tenantCode);
        dto.setCreatedBy(String.valueOf(UserService.ADMIN_USER));
        dto.setCreatedOn(new Date());
        dto.setModifiedBy(String.valueOf(UserService.ADMIN_USER));
        dto.setModifiedOn(new Date());
        return tUserMapper.updateById(dto);
    }

    @Override
    public ReturnT addOrUpdateUserForAuth(TUserPo po){
        try {
            for (String loginName:po.getLoginName()) {
                threadPoolTaskExecutor.execute(() -> {
                    addOrUpdateUser(loginName, po);
                });
            }

        }catch (Exception e){
            log.error("接收操作台传输的新增/修改用户对应角色，部门信息-{}失败...{}", JSON.toJSON(po), e.getMessage());
        }
        log.info("操作成功");
        return ReturnT.SUCCESS;
    }

    /**
     * 接收操作台传输的新增/修改用户对应角色，部门信息
     * @param loginName
     * @param po
     */
    private void addOrUpdateUser(String loginName, TUserPo po){
        // 根据用户手机号+saasCode查询用户是否存在
        UserContextHolder.setTenant(po.getSaasCode());
        QueryWrapper<TUserDTO> wrapper = new QueryWrapper<>();
        wrapper.eq("login_name", loginName);
        wrapper.eq("tenant_code", po.getSaasCode());
        TUserDTO userDTO = tUserMapper.selectOne(wrapper);
        // 数据初始化（否则后续代码通过缓存校验用户是否存在报错）
        Application.getUserStore().init(po.getSaasCode());
        if (Objects.isNull(userDTO)){
            // 新增用户
            ID userId= ID.newId(EntityHelper.User);
            TUserDTO dto = new TUserDTO();
            dto.setUserId(String.valueOf(userId));
            dto.setLoginName(loginName);
            dto.setPassword(DEFAULT_PWD);
            dto.setFullName(loginName);
            dto.setWorkphone(loginName);
            dto.setDeptId(po.getOrgId());
            dto.setRoleId(po.getRoleId().get(0));
            dto.setIsDisabled(po.getIsDisabled());
            dto.setTenantCode(po.getSaasCode());
            dto.setCreatedBy(String.valueOf(UserService.ADMIN_USER));
            dto.setCreatedOn(new Date());
            dto.setModifiedBy(String.valueOf(UserService.ADMIN_USER));
            dto.setModifiedOn(new Date());
            int result = tUserMapper.insert(dto);
            // 新用户假如USERS缓存
            Application.getUserStore().refreshUser(userId);
            if (result != 1){
                log.info("用户新增失败：{}", loginName);
                return;
            }
        }else {
            // 修改用户
            UpdateWrapper<TUserDTO> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("user_id", userDTO.getUserId());
            updateWrapper.eq("tenant_code", userDTO.getTenantCode());
            if(Objects.nonNull(po.getOrgId())){
                userDTO.setDeptId(po.getOrgId());
            }
            if (!po.getRoleId().isEmpty()){
                userDTO.setRoleId(po.getRoleId().get(0));
            }
            userDTO.setIsDisabled(po.getIsDisabled());
            userDTO.setModifiedOn(new Date());
            int result = tUserMapper.update(userDTO,updateWrapper);
            if (result != 1){
                log.info("用户修改失败：{}", loginName);
                return;
            }
            // 启动状态：刷新用户缓存
            if (po.getIsDisabled().equalsIgnoreCase("F")){
                Application.getUserStore().refreshUser(ID.valueOf(userDTO.getUserId()));
                // 禁用状态：清理用户缓存
            }else {
                Application.getUserStore().deleteUserCache(loginName, po.getSaasCode());
            }
        }
    }
    /**
     * 根据手机号码修改用户的全称，头像，邮箱信息
     * @param po
     * @return
     */
    @Override
    public ReturnT updateLtcUser(UserUpdatePO po) {
        tUserMapper.updateLtcUser(po);
        return new ReturnT();
    }

    /**
     * 交付事件回传LTC修改状态
     * @param po
     * @return
     */
    @Override
    public ReturnT updateJFEnentStatus(ApiUpdateJFStatusPO po) {
        UserContextHolder.setTenant(po.getSaasCode());
        // 判断事件类型 1：服务请求类型 2：首检服务请求
        if(po.getEventType().equals(Constant.INT_1)){
            // 事件状态（0待处理；1待开单；2已开单；3已关闭；4已拒绝）
            if (po.getEventStatus() == 1 ){
                jiaofuMapper.updateJFStatusById(po.getLtcEventId(), Constant.JF_STATUS_3, null);
            }else {
                jiaofuMapper.updateJFStatusById(po.getLtcEventId(), Constant.JF_STATUS_4, po.getReason());
            }
        } else if(po.getEventType().equals(Constant.INT_2)){
            // 事件状态（0待处理；1待开单；2已开单；3已关闭；4已拒绝）
            if (po.getEventStatus() == 1 ){
                shoujianfuwuqingqiuMapper.updateJFStatusById(po.getLtcEventId(), Constant.JF_STATUS_3, null);
            }else {
                shoujianfuwuqingqiuMapper.updateJFStatusById(po.getLtcEventId(), Constant.JF_STATUS_4, po.getReason());
            }
        }
        return ReturnT.SUCCESS;
    }

    /**
     * 采购事件回传LTC修改状态
     * @param po
     * @return
     */
    @Override
    public ReturnT updateCGEnentStatus(ApiUpdateJFStatusPO po) {
        UserContextHolder.setTenant(po.getSaasCode());
        // 事件状态（1待处理；2处理中；3已完成；4已驳回）
        if (po.getEventStatus() == 2 ){
            caigouMapper.updateCGStatusById(po.getLtcEventId(), Constant.CG_STATUS_3, null);
        }else {
            caigouMapper.updateCGStatusById(po.getLtcEventId(), Constant.CG_STATUS_4, po.getReason());
        }
        return ReturnT.SUCCESS;
    }

    /**
     * 交付事件查询合同设备列表
     * @param po
     * @return
     */
    @Override
    public ReturnT queryDeviceList(ApiQueryDevicePO po) {
        UserContextHolder.setTenant(po.getSaasCode());
        IPage<TsPrepareServiceFormEventDeviceVO> voIpage = new Page();
        List<TsPrepareServiceFormEventDeviceVO> voList = new ArrayList<>();
        // 查询交付-合同设备明细
        if (po.getType() == 0){
            Page<THetongxiangqingDTO> page = new Page<>(po.getPageNum(), po.getPageSize());
            IPage<THetongxiangqingDTO> dtoList = hetongxiangqingMapper.selectPageList(page, po);
            if (!dtoList.getRecords().isEmpty()){
                for (THetongxiangqingDTO dto : dtoList.getRecords()) {
                    TsPrepareServiceFormEventDeviceVO vo = new TsPrepareServiceFormEventDeviceVO();
                    vo.setTenantDeviceId(dto.getShebeiid());
                    vo.setDeviceVendor(dto.getRbchangshang2());
                    vo.setDeviceTypeName(dto.getShebeifenlei49());
                    vo.setDeviceTypeNo(dto.getShebeifenleibianma());
                    vo.setDeviceName(dto.getShebeixinghao());
                    vo.setSlaCode(dto.getSlabianhao());
                    vo.setSn(dto.getRbxuliehao4());
                    vo.setFuwukaishi(dto.getFuwukaishi());
                    vo.setFuwujieshu(dto.getFuwujieshu());
                    vo.setCity(dto.getRbchengshi4());
                    vo.setSupplierId(dto.getSupplierId());
                    vo.setSupplierName(dto.getGongyingshangmingcheng());
                    vo.setHetongxiangqingId(dto.getHetongxiangqingId());
                    // 返回sla详情
                    SlaAllDetailVO allDetailVO = new SlaAllDetailVO();
                    List<SlaDetailVO> slaDetailVOList = hetongxiangqingMapper.selectSlaDetail( dto.getGuanliansla());
                    allDetailVO.setServiceTime(dto.getMeizhoutian()+"*"+dto.getMeitianxiaoshi());
                    allDetailVO.setSlaDetailVOList(slaDetailVOList);
                    vo.setSlaAllDetailVO(allDetailVO);
                    voList.add(vo);
                }
                voIpage.setRecords(voList);
                voIpage.setTotal(dtoList.getTotal());
                voIpage.setCurrent(dtoList.getCurrent());
            }
            return new ReturnT(voIpage);
            // 查询交付-补充协议设备明细
        }else {
            Page<TShebeimingxibuxiaoDTO> page = new Page<>(po.getPageNum(), po.getPageSize());
            QueryWrapper<TShebeimingxibuxiaoDTO> wrapper = new QueryWrapper<>();
            wrapper.eq("BUCHONGXIEYIXIAOSHOU_ID", po.getAgreementId());
            if (Objects.nonNull(po.getSn())){
                wrapper.like("SNMAXULIEHAO", po.getSn());
            }
            IPage<TShebeimingxibuxiaoDTO> dtoList = shebeimingxibuxiaoMapper.selectPage(page, wrapper);
            if (!dtoList.getRecords().isEmpty()){
                for (TShebeimingxibuxiaoDTO dto : dtoList.getRecords()) {
                    TsPrepareServiceFormEventDeviceVO vo = new TsPrepareServiceFormEventDeviceVO();
                    vo.setTenantDeviceId(dto.getShebeiid());
                    vo.setDeviceVendor(dto.getRbchangshang5());
                    vo.setDeviceTypeName(dto.getShebeifenlei60());
                    vo.setDeviceTypeNo(dto.getShebeifenleibianma());
                    vo.setDeviceName(dto.getShebeixinghao());
                    vo.setSlaCode(dto.getSlabianhao());
                    vo.setSn(dto.getSnmaxuliehao());
                    vo.setFuwukaishi(dto.getFuwukaishiriqi());
                    vo.setFuwujieshu(dto.getFuwujieshuriqi());
                    vo.setCity(dto.getRbchengshi9());
                    voList.add(vo);
                }
                voIpage.setRecords(voList);
                voIpage.setTotal(dtoList.getTotal());
                voIpage.setCurrent(dtoList.getCurrent());
            }
            return new ReturnT(voIpage);
        }
    }

    /**
     * 应急采购订单
     * @param po
     * @return
     */
    @Override
    public ReturnT receivePmsYingJi(TYingjicaigoudingdanPO po) {
        TYingjicaigoudingdanDTO dto = new TYingjicaigoudingdanDTO();
        ID id= ID.newId(EntityHelper.Yingjicaigoudingdan);
        dto.setYingjicaigoudingdanId(id.toString());
        BeanUtils.copyProperties(po, dto);
//        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        String startDate = po.getHetongkaishishijian();
//        String endDate =po.getHetongjieshushijian();
//        dto.setHetongkaishishijian(LocalDate.parse(startDate,df));
//        dto.setHetongjieshushijian(LocalDate.parse(endDate,df));
        dto.setDingdanlaiyuan(PurchaseOrderSourceEnum.getValue(po.getDingdanlaiyuan()).getValue());// 订单来源
        dto.setDingdanleixing(PurchaseOrderTypeEnum.getValue(po.getDingdanleixing()).getValue());// 订单类型
        dto.setJiesuanfangshi(PayWayEnum.getValue(po.getJiesuanfangshi()).getValue());// 结算方式
        dto.setZhifuzhuangtai(PayStatusEnum.getValue(po.getZhifuzhuangtai()).getValue()); // 支付状态
        if(StringUtils.isNotBlank(po.getYanshoupingzhengfujian())){
            dto.setYanshoupingzhengfujian("["+po.getYanshoupingzhengfujian()+"]");
        }
        QueryWrapper<TCaigoushouhoudingdanshangpinDTO> wrapper = new QueryWrapper<>();
        wrapper.eq("yuanyingjicaigoudingdanhao", po.getCaigoudingdanhao());
        wrapper.eq("tenant_code", po.getTenantCode());
        List<TCaigoushouhoudingdanshangpinDTO> caigoushouhou = caigoushouhoudingdanshangpinMapper.selectList(wrapper);
        BigDecimal aa = BigDecimal.ZERO;
        if (!CollectionUtils.isEmpty(caigoushouhou)){
            for (TCaigoushouhoudingdanshangpinDTO dto1 : caigoushouhou) {
                aa = aa.add(dto1.getTuikuanzongjinehanshui()); // 退款总金额（含税）
            }
            dto.setYituikuanjine(aa);
            if (po.getDingdanjinehanshui() != null){
                dto.setShijidingdanjinehanshui(po.getDingdanjinehanshui().subtract(aa)); //实际金额 =订单金额 - 退款金额
            }
        }else {
            dto.setShijidingdanjinehanshui(po.getDingdanjinehanshui()); //实际金额 =订单金额

        }
        dto.setRbxiadanren9(po.getRbxiadanren());
        dto.setOwningUser(USER_ID);
        dto.setCreatedBy(USER_ID);
        dto.setModifiedBy(USER_ID);
        dto.setOwningDept(DEPT_ID);
        yingjicaigoudingdanMapper.insert(dto);
        return new ReturnT(dto.getYingjicaigoudingdanId());
    }

    /**
     * 计划采购订单
     * @param po
     * @return
     */
    @Override
    public ReturnT receivePmsJiHua(TJihuacaigoudingdanshangpinPO po) {
        TJihuacaigoudingdanshangpinDTO dto = new TJihuacaigoudingdanshangpinDTO();
        ID id= ID.newId(EntityHelper.Jihuacaigoudingdanshangpin);
        dto.setJihuacaigoudingdanshangpinId(id.toString());
        BeanUtils.copyProperties(po, dto);
//        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        String startDate = po.getHetongkaishishijian();
//        String endDate =po.getHetongjieshushijian();
//        dto.setHetongkaishishijian(LocalDate.parse(startDate,df));
//        dto.setHetongjieshushijian(LocalDate.parse(endDate,df));
        dto.setDingdanleixing(PurchaseOrderTypeEnum.getValue(po.getDingdanleixing()).getValue());// 订单类型
        dto.setJiesuanfangshi(PayWayEnum.getValue(po.getJiesuanfangshi()).getValue());// 结算方式
        dto.setZhifuzhuangtai(PayStatusEnum.getValue(po.getZhifuzhuangtai()).getValue()); // 支付状态
        dto.setRbxiadanren6(po.getRbxiadanren());
        if(StringUtils.isNotBlank(po.getYanshoupingzhengfujian())){
            dto.setYanshoupingzhengfujian("["+po.getYanshoupingzhengfujian()+"]");
        }
        QueryWrapper<TCaigoushouhoudingdanshangpinDTO> wrapper = new QueryWrapper<>();
        wrapper.eq("yuanjihuacaigoudingdanhao", po.getCaigoudingdanhao());
        wrapper.eq("tenant_code", po.getTenantCode());
        List<TCaigoushouhoudingdanshangpinDTO> caigoushouhou = caigoushouhoudingdanshangpinMapper.selectList(wrapper);
        BigDecimal aa = BigDecimal.ZERO;
        if (!CollectionUtils.isEmpty(caigoushouhou)){
            for (TCaigoushouhoudingdanshangpinDTO dto1 : caigoushouhou) {
                aa = aa.add(dto1.getTuikuanzongjinehanshui()); // 退款总金额（含税）
            }
            dto.setYituikuanjinehanshui(aa);
            if (po.getDingdanjinehanshui() != null){
                dto.setShijidingdanjinehanshui(po.getDingdanjinehanshui().subtract(aa)); //实际金额 =订单金额 - 退款金额
            }
        }else {
            dto.setShijidingdanjinehanshui(po.getDingdanjinehanshui()); //实际金额 =订单金额
        }

        dto.setRbshoujihao9(po.getXiadanrenshoujihao());
        dto.setOwningUser(USER_ID);
        dto.setCreatedBy(USER_ID);
        dto.setModifiedBy(USER_ID);
        dto.setOwningDept(DEPT_ID);
        jihuacaigoudingdanshangpinMapper.insert(dto);
        return new ReturnT(dto.getJihuacaigoudingdanshangpinId());
    }

    /**
     * 维保采购订单
     * @param po
     * @return
     */
    @Override
    public ReturnT receivePmsWeiBao(TJihuacaigouxiangmuPO po) {
        TJihuacaigouxiangmuDTO dto = new TJihuacaigouxiangmuDTO();
        ID id= ID.newId(EntityHelper.Jihuacaigouxiangmu);
        dto.setJihuacaigouxiangmuId(id.toString());
        BeanUtils.copyProperties(po, dto);
        dto.setDingdanlaiyuan(PurchaseOrderSourceEnum.getValue(po.getDingdanlaiyuan()).getValue());// 订单来源
        dto.setDingdanleixing(PurchaseOrderTypeEnum.WB.getValue());// 订单类型
        dto.setJiesuanfangshi(PayWayEnum.getValue(po.getJiesuanfangshi()).getValue());// 结算方式
        dto.setZhifuzhuangtai(PayStatusEnum.getValue(po.getZhifuzhuangtai()).getValue()); // 支付状态
        dto.setRbxiadanren7(po.getRbxiadanren());
        dto.setXiangmubianhao54(po.getCaigoudingdanhao());
        dto.setZongheshuilv(po.getShuilv());
        dto.setZhongbiaojiahanshui(po.getDingdanjinehanshui());
        dto.setOwningUser(USER_ID);
        dto.setCreatedBy(USER_ID);
        dto.setModifiedBy(USER_ID);
        dto.setOwningDept(DEPT_ID);
        jihuacaigouxiangmuMapper.insert(dto);
        return new ReturnT(dto.getJihuacaigouxiangmuId());
    }

    /**
     * 售后采购订单
     * @param po
     * @return
     */
    @Override
    public ReturnT receivePmsShouHou(TCaigoushouhoudingdanshangpinPO po) {
        TCaigoushouhoudingdanshangpinDTO dto = new TCaigoushouhoudingdanshangpinDTO();
        ID id= ID.newId(EntityHelper.Caigoushouhoudingdanshangpin);
        dto.setCaigoushouhoudingdanshangpinId(id.toString());
        BeanUtils.copyProperties(po, dto);
//        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        String startDate = po.getHetongkaishishijian();
//        String endDate =po.getHetongjieshushijian();
//        dto.setHetongkaishishijian(LocalDate.parse(startDate,df));
//        dto.setHetongjieshushijian(LocalDate.parse(endDate,df));
        dto.setDingdanlaiyuan(PurchaseOrderSourceEnum.getValue(po.getDingdanlaiyuan()).getValue());// 订单来源
        dto.setDingdanleixing(PurchaseOrderTypeEnum.getValue(po.getDingdanleixing()).getValue());// 订单类型
        dto.setShouhouleixing(AfterTypeEnum.getValue(po.getShouhouleixing()).getValue());// 售后类型
        dto.setRbxiadanren0(po.getRbxiadanren());
        dto.setOwningUser(USER_ID);
        dto.setCreatedBy(USER_ID);
        dto.setModifiedBy(USER_ID);
        dto.setOwningDept(DEPT_ID);
        // 根据采购订单编号+来源（应急/计划），修改已退款金额以及实际订单金额
        BigDecimal actual = BigDecimal.ZERO;
        if (po.getEventSource() == 1){
            List<TJihuacaigoudingdanshangpinDTO> dtoList1 = jihuacaigoudingdanshangpinMapper.selectListByCode(po.getYuanjihuacaigoudingdanhao(), po.getTenantCode());
            log.info("根据采购订单：{}:{}查询计划采购订单信息{}",po.getTenantCode(),po.getYuanjihuacaigoudingdanhao(), JSON.toJSON(dtoList1));
            if (!CollectionUtils.isEmpty(dtoList1)){
                dto.setGuanlianjihuacaigoudingdan(dtoList1.get(0).getJihuacaigoudingdanshangpinId());
                BigDecimal haveARefund = dtoList1.get(0).getYituikuanjinehanshui()==null?BigDecimal.ZERO:dtoList1.get(0).getYituikuanjinehanshui(); //已退款金额
                if (dtoList1.get(0).getShijidingdanjinehanshui() != null && (dtoList1.get(0).getShijidingdanjinehanshui().compareTo(BigDecimal.ZERO) >0)){
                    actual = dtoList1.get(0).getShijidingdanjinehanshui(); //实际订单金额
                    actual = actual.subtract(po.getTuikuanzongjinehanshui());
                }
                if (po.getTuikuanzongjinehanshui() != null){
                    haveARefund = haveARefund.add(po.getTuikuanzongjinehanshui());
                }
                jihuacaigoudingdanshangpinMapper.updateByCaiGouDan(po.getYuanjihuacaigoudingdanhao(), haveARefund, actual, po.getTenantCode());
            }
        }else if (po.getEventSource() == 2){
            List<TYingjicaigoudingdanDTO> dtoList2 = yingjicaigoudingdanMapper.selectListByCode(po.getYuanyingjicaigoudingdanhao(), po.getTenantCode());
            log.info("根据采购订单：{}:{}查询应急采购订单信息{}",po.getTenantCode(),po.getYuanyingjicaigoudingdanhao(), JSON.toJSON(dtoList2));
            if (!CollectionUtils.isEmpty(dtoList2)){
                dto.setGuanlianyingjicaigoudingdan(dtoList2.get(0).getYingjicaigoudingdanId());
                BigDecimal haveARefund = dtoList2.get(0).getYituikuanjine()==null?BigDecimal.ZERO:dtoList2.get(0).getYituikuanjine(); //已退款金额
                if (dtoList2.get(0).getShijidingdanjinehanshui() != null && (dtoList2.get(0).getShijidingdanjinehanshui().compareTo(BigDecimal.ZERO) >0)){
                    actual = dtoList2.get(0).getShijidingdanjinehanshui(); //实际订单金额
                    actual = actual.subtract(po.getTuikuanzongjinehanshui());
                }
                if (po.getTuikuanzongjinehanshui() != null){
                    haveARefund = haveARefund.add(po.getTuikuanzongjinehanshui());
                }
                yingjicaigoudingdanMapper.updateByCaiGouDan(po.getYuanyingjicaigoudingdanhao(), haveARefund, actual, po.getTenantCode());
            }
        }
        if(StringUtils.isNotBlank(po.getTuikuanfukuanpingzheng())){
            dto.setTuikuanfukuanpingzheng("["+po.getTuikuanfukuanpingzheng()+"]");
        }
        caigoushouhoudingdanshangpinMapper.insert(dto);
        return ReturnT.SUCCESS;
    }

    /**
     * 接收项目类付款
     * @param po
     * @return
     */
    @Override
    public ReturnT receivePmsItemPayment(TXiangmuleifukuanPO po) {
        TXiangmuleifukuanDTO dto = new TXiangmuleifukuanDTO();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        ID id= ID.newId(EntityHelper.Xiangmuleifukuan);
        dto.setXiangmuleifukuanId(id.toString());
        BeanUtils.copyProperties(po, dto);
        dto.setQiwangfukuanriqi(LocalDate.parse(po.getQiwangfukuanriqi(),df));
        dto.setFukuanleibie(PayTypeEnum.getValue(po.getFukuanleibie()).getValue());
        dto.setYewujieduan70(StageOfBusinessEnum.SH.getValue());
        dto.setYouwufapiao15(HaveInvoiceOrNotEnum.WFP.getValue());
        dto.setRbkaihuxing7(po.getRbkaihuxing());
        // 合同类型（0：项目合同，1：补充协议）
        if (po.getAgreementType() == Constant.INT_0){
            dto.setGuanlianhetong(po.getAgreementId());
            dto.setHetongmingcheng(po.getAgreementName());
        }else {
            // TODO 等待波波配置补充协议两个字段
        }
        dto.setOwningUser(USER_ID);
        dto.setCreatedOn(LocalDateTime.now());
        dto.setCreatedBy(USER_ID);
        dto.setModifiedOn(LocalDateTime.now());
        dto.setModifiedBy(USER_ID);
        dto.setOwningDept(DEPT_ID);
        xiangmuleifukuanMapper.insert(dto);
        return ReturnT.SUCCESS;
    }

    @Override
    public ReturnT queryRbHeTong(QueryRbHeTongPO po) {
        UserContextHolder.setTenant(po.getTenantCode());
        IPage<TRbhetong0VO> dtoList;
        if (po.getType().intValue() == 0){
            // 查询销售合同
            Page<TRbhetong0VO> page = new Page<>(po.getPageNum(), po.getPageSize());
            dtoList = rbhetong0Mapper.selectPageList(page, po);
        }else {
            // 查询框架协议
            Page<TRbhetong0VO> page = new Page<>(po.getPageNum(), po.getPageSize());
            dtoList = rbhetong0Mapper.selectFrameworkPageList(page, po);
        }
        return new ReturnT(dtoList);
    }

    @Override
    public ReturnT createInquiryToLtc(TBaojiaxietongPO po) {
        TBaojiaxietongDTO dto = new TBaojiaxietongDTO();
        BeanUtils.copyProperties(po, dto);
        ID id= ID.newId(EntityHelper.BaoJiaXieTong);
        dto.setBaojiaxietongId(id.toString());
        UserContextHolder.setTenant(po.getTenantCode());
        QueryWrapper<TUserDTO> wrapper = new QueryWrapper<>();
        wrapper.eq("login_name", po.getCreateUser());
        wrapper.eq("tenant_code", po.getTenantCode());
        TUserDTO userDTO = tUserMapper.selectOne(wrapper);
        if (Objects.isNull(userDTO)){
            log.info("根据租户{}和手机号{}查询不到创建人",po.getTenantCode(), po.getCreateUser());
            return ReturnT.FAIL;
        }
        if(StringUtils.isNotBlank(po.getMingxifujian())){
            dto.setMingxifujian("["+po.getMingxifujian()+"]");
        }
        ClassificationDataDTO dataDTO = classificationDataMapper.selectByCode(po.getSuozaichengshi(), po.getTenantCode());
        if (dataDTO != null){
            dto.setSuozaichengshi(dataDTO.getItemId());
        }else {
            dto.setSuozaichengshi(null);
        }
        dto.setYewuleixing(BusinessTypeEnum.getValue(po.getYewuleixing()).getValue());
        dto.setSuoshuhangye(IndustryEnum.getValue(po.getSuoshuhangye()).getValue());
        dto.setOwningUser(userDTO.getUserId());
        dto.setCreatedBy(userDTO.getUserId());
        dto.setModifiedBy(userDTO.getUserId());
        dto.setOwningDept(userDTO.getDeptId());
        baojiaxietongMapper.insert(dto);
        return ReturnT.SUCCESS;
    }

    /**
     * 根据报价单ID修改报价单数据
     * @param po
     * @return
     */
    @Override
    public ReturnT updateQuotationToLtc(UpdateQuotePO po) {
        // 解析附件
        if(StringUtils.isNotBlank(po.getPdfUrl())){
            po.setPdfUrl("['"+po.getPdfUrl()+"']");
        }
        int result = quotationMapper.updateQuotationToLtc(po);
        if (result != -1){
            log.info("修改报价单成功");
            // 根据报价单的关联商机修改对应商机下的字段
            quotationMapper.updateShangJiToLtc(po);
            log.info("根据报价单id修改对应商机下的报价金额，综合税率");
            return new ReturnT("修改报价单成功");
        }else {
            log.info("修改报价单失败");
            return new ReturnT(500,"修改报价单失败");
        }
    }

    /**
     *  APP-查询企业下销售云用户
     * @param param
     * @return
     */
    @Override
    public ReturnT selectLtcUserList(String param) {
        Map<String, List<ApiUserVO>> result = new HashMap<>();
        QueryWrapper<TUserDTO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("IS_DISABLED", "F");
        if (StringUtils.isNotBlank(param)){
            queryWrapper.and(wrapper -> wrapper.like("login_name", param).or().like("full_name", param));
        }
        List<TUserDTO> userDTOS = tUserMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(userDTOS)){
            return new ReturnT(result);
        }
        String english="[a-zA-Z]";
        for (TUserDTO dto : userDTOS) {
            //调用工具类方法获取汉字串拼音
            String zm = NameUtil.getFullSpell(dto.getFullName()).substring(0, 1);
            if (!zm.matches(english)){
                zm = "#";
            }
            // 将26个字母 和遍历出来接触的首字母比较相同添加到集合
            ApiUserVO vo = new ApiUserVO();
            BeanUtils.copyProperties(dto, vo);
            if (StringUtils.isNotBlank(vo.getAvatarUrl())){
                if (vo.getAvatarUrl().startsWith("rb/")){
                    String attachmentUrl = RebuildConfiguration.getByTenantCode(ConfigurationItem.StorageURL,false, UserContextHolder.getTenant());
                    vo.setAvatarUrl(attachmentUrl+vo.getAvatarUrl());
                }
            }
            if (result.containsKey(zm)) {
                result.get(zm).add(vo);
            }else {
                List<ApiUserVO> vos = new ArrayList<>();
                vos.add(vo);
                result.put(zm, vos);
            }
        }
        return new ReturnT(result);
    }

    @Override
    public ReturnT projectReportDayData(List<AddProjectReportPO> poList) {
        for (AddProjectReportPO po:poList ){
            TProjectReportDTO dto = new TProjectReportDTO();
            BeanUtils.copyProperties(po, dto);
            String reportId = IdUtil.simpleUUID();
            dto.setReportId(reportId);
            dto.setCreatedBy(USER_ID);
            dto.setModifiedBy(USER_ID);
            log.info("定时保存新增项目报表数据");
            tProjectReportMapper.insertProjectReport(dto);
        }
        return ReturnT.SUCCESS;
    }

    @Override
    public ReturnT delProjectReportDayData() {
        int r= tProjectReportMapper.deleteNoTenantCode("LTC");
        return r<0?ReturnT.FAIL:ReturnT.SUCCESS;
    }

    /**
     * 新增/修改企业供应商信息
     * @param poList
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
    public ReturnT receiveSupplierInfo(List<AddSupplierPO> poList) {
        int count = 0;
        for (AddSupplierPO po : poList) {
            // 判断租户标识是否存在，不存在则忽略
            if (StringUtils.isNotBlank(po.getTenantCode())){
                // 根据被服务企业租户标识+供应商ID查询供应商表删除
                TGongyingshangguanliDTO dto = new TGongyingshangguanliDTO();
                BeanUtils.copyProperties(po, dto);
                TGongyingshangguanliDTO selectDto = gongyingshangguanliMapper.selectBySupplierId(po.getTenantCode(), po.getSupplierTenantId());
                if (selectDto !=null){
                    dto.setGongyingshangguanliId(String.valueOf(selectDto.getGongyingshangguanliId()));
                    gongyingshangguanliMapper.updateByIdAndTenantCode(dto);
                }else {
                    ID id= ID.newId(EntityHelper.Gongyingshangguanli);
                    dto.setGongyingshangguanliId(String.valueOf(id));
                    dto.setCreatedBy(USER_ID);
                    dto.setModifiedBy(USER_ID);
                    dto.setOwningDept(DEPT_ID);
                    dto.setOwningUser(USER_ID);
                    dto.setWeiyiid(po.getSupplierTenantId());
                    dto.setGongyingshangleixing(SupplierTypeEnum.getValue(po.getSupplierType()).getValue()); //供应商类型
                    gongyingshangguanliMapper.insertSupplier(dto);
                }
                count = count++;
            }
        }
        return new ReturnT(200, "操作成功"+count+"条");
    }

    @Override
    public ReturnT deleteSupplierInfo(List<DeleteSupplierPO> poList) {
        int count = 0;
        for (DeleteSupplierPO po : poList) {
            // 判断租户标识是否存在，不存在则忽略
            if (StringUtils.isNotBlank(po.getTenantCode())){
                // 根据被服务企业租户标识+供应商ID查询供应商表删除
                int d = gongyingshangguanliMapper.deleteBySupplierId(po.getTenantCode(), po.getSupplierTenantId());
                count = count+d;
            }
        }
        return new ReturnT(200, "操作成功"+count+"条");
    }

    /**
     * 接收交付云首检设备明细接口
     * @param po
     * @return
     */
    @Override
    public ReturnT receiveTsEquipmentDetails(List<LtcInspectionPO> po) {
        // 根据上游销售云首检服务请求ID 查询首检服务请求中的超能宝商机ID
        QueryWrapper<TShoujianfuwuqingqiuDTO> wrapper = new QueryWrapper();
        wrapper.eq("SHOUJIANFUWUQINGQIU_ID", po.get(0).getLtcEventId());
        TShoujianfuwuqingqiuDTO eventDto = shoujianfuwuqingqiuMapper.selectOne(wrapper);
        if (Objects.isNull(eventDto)){
            log.info("查不到首检服务请求:{}", po.get(0).getLtcEventId());
            return new ReturnT(500, "查不到首检服务请求:"+po.get(0).getLtcEventId());
        }
        // 将上游商机设备明细存储到【首检设备明细】中
        int i= 0;
        for (LtcInspectionPO p : po){
            TShebeimingxichaonengbaoDTO dto = new TShebeimingxichaonengbaoDTO();
            // 首检设备明细（超能宝）
            ID id= ID.newId(EntityHelper.Shebeimingxichaonengbao);
            dto.setShebeimingxichaonengbaoId(String.valueOf(id));
            // 超能宝商机ID
            dto.setRbshangji1Id(eventDto.getGuanlianshangji());
            // 设备型号
            dto.setShebeixinghao(p.getBrandModel());
            // 厂商
            dto.setRbchangshang3(p.getBrandName());
            // 出厂日期
            dto.setChuchangriqi(p.getDateProduction());
            // SN码
            dto.setRbsnma4(p.getEquipmentSn());
            // 赋码
            dto.setRbfuma0(p.getCodeNumber());
            // 是否满足保司投保
            dto.setShifoumanzubaositoubao(p.getInsureFlag()==1?"F":"T");
            // 新机价格
            dto.setXinjijiage(p.getProductPrice());
            // 超能保报价
            dto.setCnbQuote(p.getCnbQuote());
            dto.setTenantCode(p.getSaasCode());
            dto.setCreatedBy(String.valueOf(UserService.ADMIN_USER));
            dto.setModifiedBy(String.valueOf(UserService.ADMIN_USER));
            shebeimingxichaonengbaoMapper.insert(dto);
            i++;
        }
        return new ReturnT("保存首检设备明细（超能宝）成功"+i+"条");
    }

    /**
     * 功能描述: APP新需求-查询消息/待办的审批
     *
     * @Param: [po]
     * @Return: com.xxl.sso.core.entity.ReturnT
     * @Author: wrj
     * @Date: 2022/4/21 5:15 下午
     */
    @Override
    public ReturnT apiApprovalList(ApprovalListQueryPO po) {
        po.setTenantCode(UserContextHolder.getTenant());
        po.setCurrentUser(UserContextHolder.getUser().toString());
        Page<RobotApprovalStepVO> page = new Page<>(po.getPageNum(), po.getPageSize());
        IPage<RobotApprovalStepVO> stepDTOIPage = null;
        // 查询待处理审批列表
        if (po.getDealWithFlag() == 1){
            stepDTOIPage = robotApprovalStepMapper.pendingApprovalList(page, po);
            // 查询已处理审批列表
        }else if (po.getDealWithFlag() == 2){
            // state == 0 说明是全查已处理审批数据需要(in 查询通过，撤回，撤销，驳回的数据)
            if (po.getState() == 0){
                stepDTOIPage = robotApprovalStepMapper.processedApprovalList(page, po);
                // 根据审批条件专门查询 state = ？
            }else {
                stepDTOIPage = robotApprovalStepMapper.processedApprovalListByState(page, po);
            }
            // 我提交的
        }else if (po.getDealWithFlag() == 4){
            stepDTOIPage = robotApprovalStepMapper.processedApprovalListBySubmitted(page, po);
        }

        // 数据处理
        if (CollectionUtils.isNotEmpty(stepDTOIPage.getRecords())){
            List<RobotApprovalStepVO> voList = new ArrayList<>();
            List<RobotApprovalStepVO> records = stepDTOIPage.getRecords();
            for (RobotApprovalStepVO record : records) {
                ID recordId = ID.valueOf(record.getRecordId());
                // 数据当前状态
                final ApprovalState currentState = ApprovalHelper.getApprovalState(recordId);
                // 数据对应实体
                Entity entity = MetadataHelper.getEntity(recordId.getEntityCode());

                // 审批发起人
                StringBuilder sql = new StringBuilder("select ");
                sql.append("createdBy, createdOn ")
                        .append(" from ")
                        .append(entity.getName())
                        .append(" where ")
                        .append(entity.getPrimaryField().getName())
                        .append(" = ?")
                        .append(" and tenantCode = ?");
                Record r = Application.getQueryFactory().createQuery(sql.toString(), UserService.ADMIN_USER)
                        .setParameter(1, recordId)
                        .setParameter(2, UserContextHolder.getTenant())
                        .record();
                if (r == null){
                    log.info("根据数据ID查询不到数据:{}", record.getRecordId());
                    return new ReturnT();
                }

                // 审批发起人
                ID s = ApprovalHelper.getSubmitter(recordId, ID.valueOf(record.getApprovalId()), UserContextHolder.getTenant());
                // 创建人
                record.setCreatedBy(UserHelper.getName(s));
                record.setCreatedOn(DateUtil.format(r.getDate("createdOn"), "yyyy-MM-dd HH:mm:ss"));

                // 数据唯一编号
                String label;
                try {
                    label = FieldValueHelper.getLabel(recordId);
                } catch (NoRecordFoundException ignored) {
                    label = EasyMetaFactory.getLabel(entity);
                }
                record.setLabel(label);
                // 数据实体名称
                record.setEntityName(EasyMetaFactory.getLabel(entity));
                // 实体编码
                record.setEntityCode(entity.getName());
                // 数据当前状态
                record.setState(currentState.getName());
                voList.add(record);
            }
            stepDTOIPage.setRecords(voList);
        }

        return new ReturnT(stepDTOIPage);
    }

    @Override
    public ReturnT apiCcApprovalList(List<RobotApprovalStepVO> relatedRecords) {

        // 数据处理
        if (CollectionUtils.isEmpty(relatedRecords)) {
            return new ReturnT();
        }
        List<RobotApprovalStepVO> voList = new ArrayList<>();
        for (RobotApprovalStepVO record : relatedRecords) {
            ID recordId = ID.valueOf(record.getRecordId());
            // 数据当前状态
            final ApprovalState currentState = ApprovalHelper.getApprovalState(recordId);
            // 数据对应实体
            Entity entity = MetadataHelper.getEntity(recordId.getEntityCode());
            // 审批发起人
            StringBuilder sql = new StringBuilder("select ");
            sql.append(" approvalId, createdBy, createdOn ")
                .append(" from ")
                .append(entity.getName())
                .append(" where ")
                .append(entity.getPrimaryField().getName())
                .append(" = ?")
                .append(" and tenantCode = ?");
            Record r = Application.getQueryFactory().createQuery(sql.toString(), UserService.ADMIN_USER)
                    .setParameter(1, recordId)
                    .setParameter(2, UserContextHolder.getTenant())
                    .record();
            if (r == null){
                log.info("根据数据ID查询不到数据:{}", record.getRecordId());
                return new ReturnT();
            }
            // 创建人
            record.setCreatedBy(UserHelper.getName(r.getID("createdBy")));
            record.setApprovalId(r.getID("approvalId").toString());
            record.setCreatedOn(DateUtil.format(r.getDate("createdOn"), "yyyy-MM-dd HH:mm:ss"));
            // 数据唯一编号
            String label;
            try {
                label = FieldValueHelper.getLabel(recordId);
            } catch (NoRecordFoundException ignored) {
                label = EasyMetaFactory.getLabel(entity);
            }
            record.setLabel(label);
            // 数据实体名称
            record.setEntityName(EasyMetaFactory.getLabel(entity));
            // 实体编码
            record.setEntityCode(entity.getName());
            // 数据当前状态
            record.setState(currentState.getName());
            voList.add(record);
        }
        return new ReturnT(voList);
    }

    /**
     * 功能描述: 接收采购云-采购订单数据
     *
     * @Param: [po]
     * @Return: com.xxl.sso.core.entity.ReturnT
     * @Author: wrj
     * @Date: 2022/5/5 3:55 下午
     */
    @Override
    public ReturnT receivePmsPurchaseOrder(PmsPurchaseOrderPO po) {
        ID userId = UserContextHolder.getUser();
        User checkedUser = Application.getUserStore().getUser(userId);
        QueryWrapper<TCaiGouDingDanGuiJiDTO> wrapper = new QueryWrapper<>();
        wrapper.eq("CAIGOUDINGDANHAO", po.getCaigoudingdanhao());
        wrapper.eq("TENANT_CODE", UserContextHolder.getTenant());
        TCaiGouDingDanGuiJiDTO d = caiGouDingDanGuiJiMapper.selectOne(wrapper);
        if (d != null){
            return new ReturnT(500, "订单已推送，不能再次推送");
        }
        TCaiGouDingDanGuiJiDTO dto = new TCaiGouDingDanGuiJiDTO();
        ID id= ID.newId(EntityHelper.Caigoudingdanguiji);
        dto.setCaigoudingdanguijiId(id.toString());
        BeanUtils.copyProperties(po, dto);
        dto.setDingdanlaiyuan(PurchaseOrderSourceEnum.getValue(po.getDingdanlaiyuan()).getValue());// 订单来源
        dto.setDingdanleixing(PurchaseOrderTypeEnum.getValue(po.getDingdanleixing()).getValue());// 订单类型
        dto.setJiesuanfangshi(PayWayEnum.getValue(po.getJiesuanfangshi()).getValue());// 结算方式
        dto.setZhifuzhuangtai(PayStatusEnum.getValue(po.getZhifuzhuangtai()).getValue()); // 支付状态
        if(StringUtils.isNotBlank(po.getYanshoupingzhengfujian())){
            dto.setYanshoupingzhengfujian("["+po.getYanshoupingzhengfujian()+"]");
        }
        try {
            dto.setHetongkaishishijian(LocalDateTime.parse(po.getHetongkaishishijian(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            dto.setHetongjieshushijian(LocalDateTime.parse(po.getHetongjieshushijian(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }catch (Exception e){
            log.info("合同时间转换异常：{}", e.getMessage());
        }
        // 采购订单状态
        dto.setDingdanzhuangtai(po.getOrderStatus());
        dto.setRbxiadanren9(po.getRbxiadanren());
        dto.setOwningUser(userId.toString());
        dto.setCreatedBy(userId.toString());
        dto.setModifiedBy(userId.toString());
        dto.setOwningDept(checkedUser.getOwningDept().getIdentity().toString());
        caiGouDingDanGuiJiMapper.insert(dto);
        // 保存采购订单明细表
        savePmsOrderDetail(po, id, userId.toString());

        return new ReturnT(dto.getCaigoudingdanguijiId());
    }

    /**
     * 功能描述:保存采购订单明细表
     *
     * @Param: []
     * @Return: void
     * @Author: wrj
     * @Date: 2022/5/7 11:24 上午
     */
    public void savePmsOrderDetail(PmsPurchaseOrderPO po, ID id, String userId){
        // 设备信息
        if (CollectionUtils.isNotEmpty(po.getEquipmentDetailList())){
            for (TCaiGouDingDanEquipmentPO po1 : po.getEquipmentDetailList()){
                TCaiGouDingDanMingXiGuiJiDTO dto = new TCaiGouDingDanMingXiGuiJiDTO();
                BeanUtils.copyProperties(po1, dto);
                // 采购订单ID
                dto.setCaigoudingdanguijiId(id.toString());
                ID dId= ID.newId(EntityHelper.Caigoudingdanmingxiguiji);
                // 采购订单明细ID
                dto.setCaigoudingdanmingxiguijiId(dId.toString());
                dto.setCreatedBy(userId);
                dto.setModifiedBy(userId);
                caiGouDingDanMingXiGuiJiMapper.insert(dto);
            }
            // 工程师信息
        } else if (CollectionUtils.isNotEmpty(po.getEngineerDetailList())){
            for (TCaiGouDingDanEngineerPO po1 : po.getEngineerDetailList()){
                TCaiGouDingDanMingXiGuiJiDTO dto = new TCaiGouDingDanMingXiGuiJiDTO();
                BeanUtils.copyProperties(po1, dto);
                // 采购订单ID
                dto.setCaigoudingdanguijiId(id.toString());
                ID dId= ID.newId(EntityHelper.Caigoudingdanmingxiguiji);
                // 采购订单明细ID
                dto.setCaigoudingdanmingxiguijiId(dId.toString());
                dto.setCreatedBy(userId);
                dto.setModifiedBy(userId);
                caiGouDingDanMingXiGuiJiMapper.insert(dto);
            }
            // 备件信息
        } else if (CollectionUtils.isNotEmpty(po.getPartsDetailList())){
            for (TCaiGouDingDanPartsPO po1 : po.getPartsDetailList()){
                TCaiGouDingDanMingXiGuiJiDTO dto = new TCaiGouDingDanMingXiGuiJiDTO();
                BeanUtils.copyProperties(po1, dto);
                // 采购订单ID
                dto.setCaigoudingdanguijiId(id.toString());
                ID dId= ID.newId(EntityHelper.Caigoudingdanmingxiguiji);
                // 采购订单明细ID
                dto.setCaigoudingdanmingxiguijiId(dId.toString());
                dto.setCreatedBy(userId);
                dto.setModifiedBy(userId);
                caiGouDingDanMingXiGuiJiMapper.insert(dto);
            }
            // 服务信息
        } else if (CollectionUtils.isNotEmpty(po.getServiceInfoDetailList())){
            for (TCaiGouDingDanServicePO po1 : po.getServiceInfoDetailList()){
                TCaiGouDingDanMingXiGuiJiDTO dto = new TCaiGouDingDanMingXiGuiJiDTO();
                BeanUtils.copyProperties(po1, dto);
                // 采购订单ID
                dto.setCaigoudingdanguijiId(id.toString());
                ID dId= ID.newId(EntityHelper.Caigoudingdanmingxiguiji);
                // 采购订单明细ID
                dto.setCaigoudingdanmingxiguijiId(dId.toString());
                dto.setCreatedBy(userId);
                dto.setModifiedBy(userId);
                caiGouDingDanMingXiGuiJiMapper.insert(dto);
            }
        }

    }


    /**
     * 功能描述:修改采购云的采购订单状态
     *
     * @Param: [po]
     * @Return: com.xxl.sso.core.entity.ReturnT
     * @Author: wrj
     * @Date: 2022/5/5 4:08 下午
     */
    @Override
    public ReturnT updatePmsPurchaseOrder(PmsUpdatePurchaseOrderPO po) {
        // 根据订单号查询采购订单
        log.info("参数备件PN不为空，则先根据采购单号查询采购单信息:{}", po.getCaigoudingdanhao());
        QueryWrapper<TCaiGouDingDanGuiJiDTO> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("CAIGOUDINGDANHAO", po.getCaigoudingdanhao());
        List<TCaiGouDingDanGuiJiDTO> dtos = caiGouDingDanGuiJiMapper.selectList(wrapper1);
        if (CollectionUtils.isEmpty(dtos)){
            log.info("采购单号不存在：{}", po.getCaigoudingdanhao());
            return new ReturnT(500, "采购单号不存在："+po.getCaigoudingdanhao());
        }

        // 状态不为空，修改采购订单状态
        if(po.getOrderStatus() != null){
            caiGouDingDanGuiJiMapper.updateByCaiGouDan(po.getCaigoudingdanhao(), po.getOrderStatus(), UserContextHolder.getTenant());
        }
        // 备件明细不为空，则修改备件PN，保存对应的物流信息和SN信息
        if (CollectionUtils.isNotEmpty(po.getPartsDetailList())){
            for (TCaiGouDingDanPartsUpdatePO partsUpdatePO : po.getPartsDetailList()) {
                // 根据采购订单id查询采购订单明细
                log.info("根据采购订单id+备件PN{}查询采购订单明细:{}", partsUpdatePO.getBeijianpn(), po.getCaigoudingdanhao());
                QueryWrapper<TCaiGouDingDanMingXiGuiJiDTO> wrapper2 = new QueryWrapper<>();
                wrapper2.eq("CAIGOUDINGDANGUIJI_ID", dtos.get(0).getCaigoudingdanguijiId());
                wrapper2.eq("BEIJIANPN", partsUpdatePO.getBeijianpn());
                List<TCaiGouDingDanMingXiGuiJiDTO> mingXiDtos = caiGouDingDanMingXiGuiJiMapper.selectList(wrapper2);
                if (CollectionUtils.isNotEmpty(mingXiDtos)){
                    // 修改备件PN对应的SN，物流公司，物流信息
                    TCaiGouDingDanMingXiGuiJiDTO mingXiDto = new TCaiGouDingDanMingXiGuiJiDTO();
                    mingXiDto.setCaigoudingdanmingxiguijiId(mingXiDtos.get(0).getCaigoudingdanmingxiguijiId());
                    mingXiDto.setBeijiansn(partsUpdatePO.getBeijiansn());
                    mingXiDto.setWuliugongsi(partsUpdatePO.getWuliugongsi());
                    mingXiDto.setWuliudanhao(partsUpdatePO.getWuliudanhao());
                    log.info("根据采购订单明细中备件PN修改备件PN对应的SN，物流公司，物流信息:{}", JSON.toJSON(mingXiDto));
                    caiGouDingDanMingXiGuiJiMapper.updateById(mingXiDto);
                }
            }
        }

        // 由于采购云那边，驻场服务只有在派单的时候才知道哪个工程师，所以走修改接口
        if (CollectionUtils.isNotEmpty(po.getEngineerDetailList())){
            for (TCaiGouDingDanEngineerPO po1:po.getEngineerDetailList()) {
                TCaiGouDingDanMingXiGuiJiDTO dto = new TCaiGouDingDanMingXiGuiJiDTO();
                BeanUtils.copyProperties(po1, dto);
                // 采购订单ID
                dto.setCaigoudingdanguijiId(dtos.get(0).getCaigoudingdanguijiId());
                ID dId= ID.newId(EntityHelper.Caigoudingdanmingxiguiji);
                // 采购订单明细ID
                dto.setCaigoudingdanmingxiguijiId(dId.toString());
                dto.setCreatedBy(dtos.get(0).getCreatedBy());
                dto.setModifiedBy(dtos.get(0).getModifiedBy());
                caiGouDingDanMingXiGuiJiMapper.insert(dto);
            }
        }
        return ReturnT.SUCCESS;
    }
}
